//
//  HCoreConfig.m
//  HMusicPlayer
//
//  Created by Hament on 14/9/5.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "HCoreConfig.h"
#import <CommonCrypto/CommonDigest.h>
#import "HskinManager.h"
#import "HSQLManager.h"
#import <AudioToolbox/AudioToolbox.h>
#import "HSongItem.h"
#import "TagReader.h"
#import "iTunes.h"
#import "HJAudioPlayer.h"
#import <QuartzCore/QuartzCore.h>
#import <AVFoundation/AVFoundation.h>

#import <OrigamiEngine/ORGMConverter.h>
#import <OrigamiEngine/ORGMInputUnit.h>
#import <OrigamiEngine/ORGMOutputUnit.h>
@interface HCoreConfig ()


@property (nonatomic,strong) iTunesApplication *iTunes;

@property (nonatomic,strong)CIFilter * colorFilter;



@end

@implementation HCoreConfig



#pragma mark singleon
static HCoreConfig * cofig=nil;
+(HCoreConfig *)shareConfig{
    
    @synchronized( self )
    {
        if (cofig==nil) {
            cofig=[[HCoreConfig alloc] init];
            
        }
    }
    return cofig;
}



-(id)init{
    self=[super init];
    
    if (self) {
        
        
        
        //音乐文件夹路径
        self.musicDocumentPath=HMusicDirectory;
        
        debugLog(@"caches:%@",HCachesDirectory);
        //        NSURL * musicDurl=[NSURL fileURLWithPath:self.musicDocumentPath];
        //
        //        if ([musicDurl isFileReferenceURL]) {
        //            debugLog(@"fileReferenceURL:");
        //
        //        }
        
        //设置所使用的语言档
        NSArray *languages = GetUserDefaultsWithKey(@"AppleLanguages");
        NSString *preferredLang = CHECKSTR([languages objectAtIndex:0]);//用户系统当前使用的语言
        //debugLog(@"preferredLang:%@",preferredLang);
        if ([preferredLang isEqualToString:@""]) {
            SetUserDefaultsForKey(UseLanguage, @"en");
        }
        
        else {
            SetUserDefaultsForKey(UseLanguage, preferredLang);
        }
        
        //app version
        NSDictionary *_infoDictionary = [[NSBundle mainBundle] infoDictionary];
        self.currentAppVersion = [_infoDictionary objectForKey:@"CFBundleVersion"];
        
        
        //pro or lite
        NSString * bundleid=[_infoDictionary objectForKey:@"CFBundleIdentifier"];
        if ([bundleid isEqualToString:@"hj.gladMusic.osx.pro"]) {
            self.isPro=YES;
        } else {
            self.isPro=NO;
        }

        
        
        NSFileManager * filemanager=[NSFileManager defaultManager];
        BOOL isdir=NO;
        //----建立网上资源缓存文件夹-----
        
        //music
        if ([filemanager fileExistsAtPath:musicCache isDirectory:&isdir]==NO || isdir==NO) {
            [filemanager createDirectoryAtPath:musicCache withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        //lyrics
        isdir=NO;
        if ([filemanager fileExistsAtPath:lyricsCache isDirectory:&isdir]==NO || isdir==NO) {
            [filemanager createDirectoryAtPath:lyricsCache withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        //album
        isdir=NO;
        if ([filemanager fileExistsAtPath:albumCache isDirectory:&isdir]==NO || isdir==NO) {
            [filemanager createDirectoryAtPath:albumCache withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        
        
        //复制歌曲数据库
        if ([filemanager fileExistsAtPath:songDBPath]==NO) {
            NSString * path=fileBundlePath(@"song",@"db");
            [filemanager copyItemAtPath:path toPath:songDBPath error:nil];
        }
        
        
        
        
        //-----配置skin-----
        
        //1.首先建立对应放置皮肤的文件夹
        isdir=NO;
        if ([filemanager fileExistsAtPath:skinConfigFolder isDirectory:&isdir]==NO || isdir==NO) {
            [filemanager createDirectoryAtPath:skinConfigFolder withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
#ifdef DEBUG
        //测试,保持同步
      //  [filemanager removeItemAtPath:skinConfigPath error:nil];
#endif
        
        //2.如果配置文件不存在,copy默认skinconfig
        if ([filemanager fileExistsAtPath:skinConfigPath]==NO) {
            NSString * path=fileBundlePath(@"defaultSkinConfig",@"plist");
            [filemanager copyItemAtPath:path toPath:skinConfigPath error:nil];
        }
        
        //3.加载皮肤配置
        self.currentSkinManager=[[HskinManager alloc] initWithConfigPath:skinConfigPath];
        self.colorFilter=[CIFilter filterWithName:@"CIMultiplyCompositing"];
        [self refreshSkinImage];//刷新全局图片
        
    }
    
    
    self.holdWindoControllerArr=[NSMutableArray arrayWithCapacity:3];
    
    
    return self;
}


#pragma mark --------------实例方法----------
//获取语言
- (NSString *) getUserLang{
    return GetUserDefaultsWithKey(UseLanguage);
    
}


-(iTunesApplication*)iTunes{
    if (!_iTunes) {
        _iTunes=[SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
    }
    return _iTunes;
}

/*
 #pragma mark 是否导入itunes playlist
 
 -(void)setIsImportItunesPl:(BOOL)flag{
 
 [[NSUserDefaults standardUserDefaults] setBool:flag forKey:IsImportItunesPlaylist];
 [[NSUserDefaults standardUserDefaults] synchronize];
 _isImportItunesPl=flag;
 
 }
 
 -(BOOL)isImportItunesPl{
 
 //默认不导入
 BOOL flag = [[NSUserDefaults standardUserDefaults] boolForKey:IsImportItunesPlaylist];
 return flag;
 }
 */


#pragma  mark 根据版本更新数据库
-(BOOL)isNeedUpdateDB{
    BOOL isneed=NO;
    
    NSString * recordVersion=[HSQLManager getappVersionInDB];//这个版本号应该和安装时候的app版本号一致
    
    NSDictionary *_infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString * currentversion = [_infoDictionary objectForKey:@"CFBundleVersion"];
    
    if ([recordVersion compare:currentversion]==NSOrderedAscending) {
        isneed=YES;
    }
    
    return isneed;
}



#pragma  mark 刷新使用的全局图片
-(void)refreshSkinImage{
    
    //删除歌曲
    self.delSongNorImg=[self getImageWithMainBundle:@"icon_del_nml"];
    self.delSongHltImg=[self getImageWithMainBundle:@"icon_del_hlt"];
    
    //like song
    self.likeSongImg=[self getImageWithMainBundle:@"icon_like_hlt"];
    self.unlikeSongImg=[self getImageWithMainBundle:@"icon_like_nml"];
    
    //添加playlist
    self.addPlaylistNorImg=[self getImageWithMainBundle:@"icon_playlist_new_nml"];
    self.addPlaylistHltImg=[self getImageWithMainBundle:@"icon_playlist_new_hlt"];
    
    
}



#pragma mark /*----------------字符串处理-------------*/
//字符串替换
+(NSString *) ReplaceFirstNewLine:(NSString * )original symbol:(NSString*)symbol replaceWith:(NSString*)replaceStr{
    
    /*
     NSMutableString *mstring = [NSMutableString stringWithString:original];
     NSRange wholeShebang = NSMakeRange(0, [mstring length]);
     [mstring replaceOccurrencesOfString: symbol
     withString: replaceStr
     options: 0
     range: wholeShebang];
     return [NSString stringWithString:mstring];
     */
    
    //  NSLog(@"数字： %@",[NSString stringWithString:mstring]);
    
    NSString * des=[original stringByReplacingOccurrencesOfString:symbol withString:replaceStr];
    return  des;
    
    
    
}




//快速去除html<> 标记
+(NSString *) stringByStrippingHTML:(NSString*)htmlstr {
    NSRange r;
    NSString *s =[NSString stringWithString:htmlstr];
    while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
        s = [s stringByReplacingCharactersInRange:r withString:@""];
    return s;
}

//milesecond To MM:SS
+(NSString* )convertMileSecond:(NSUInteger)duration{
    
    
    NSUInteger min=duration/(60*1000);
    NSUInteger second=ceil((duration/1000)%60); //
    
    NSString * time=[NSString stringWithFormat:@"%d:%.2d",min,second];
    
    return time;
}

#pragma mark /*----------------数据类型转换处理-------------*/
#pragma mark number To String
+(NSString*)numberToString:(id)numvalue{
    
    id thevalue=CHECKSTR(numvalue);
    if ([thevalue isKindOfClass:[NSNumber class]]) {
        return [thevalue stringValue];
    }
    
    return thevalue;
}



#pragma mark /*----------------其他-------------*/

//MD5生成
+(NSString*)generateMD5Hash{
    
    NSDateFormatter *  currentMD5DateFormatter=[[NSDateFormatter alloc] init];
    NSDate * date=[NSDate date];
    [currentMD5DateFormatter  setDateFormat: @"yyyy-MM-dd HH:mm:ss.SSS"];
    NSString * dateStr=[currentMD5DateFormatter stringFromDate:date];
    
    const char *cStr= [dateStr UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), result);
    return [NSString stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ];
}

//纳秒
+(NSString*)generateSyncID{
    
    NSString * generateSyncID=[NSString stringWithFormat:@"%lf",CFAbsoluteTimeGetCurrent()];//
    return generateSyncID;
}



#pragma mark /*----------------业务逻辑-------------*/

#pragma mark ----设置当前播放信息


#pragma mark检测是否无损歌曲
+(BOOL)checkLosslessWithSongItem:(HSongItem*)songitem{
    NSString * ext=CHECKSTR([songitem.localPath pathExtension]);
    //本地
    if (![ext isEqualToString:@""]) {
        ext=[ext lowercaseString];
        if([ext isEqualToString:@"flac"] || [ext isEqualToString:@"opus"]) {
            return YES;
        }
        
    }
    //online
    else {
        ext=CHECKSTR([songitem.urlPath pathExtension]);
        
        if(![ext isEqualToString:@""]) {
            ext=[ext lowercaseString];
            if([ext isEqualToString:@"flac"] || [ext isEqualToString:@"opus"]) {
                return YES;
            }
        }
        
    }
    
    return NO;
}

#pragma mark------获取aac/m4a 图片
+(void)getSoundPropertyWithPath:(NSString*)path completion:(void (^)(NSDictionary*))completion{

    BOOL exist=[[NSFileManager defaultManager] fileExistsAtPath:path];
    if (exist) {
        NSURL *u = [NSURL fileURLWithPath:path];
        AVURLAsset *a = [AVURLAsset URLAssetWithURL:u options:nil];
    
        NSArray *k = [NSArray arrayWithObjects:@"commonMetadata", nil];
        [a loadValuesAsynchronouslyForKeys:k completionHandler:^{
            
            NSArray *artworks = [AVMetadataItem metadataItemsFromArray:a.commonMetadata
                                                               withKey:AVMetadataCommonKeyArtwork keySpace:AVMetadataKeySpaceCommon];
            NSImage *im = nil;
            for (AVMetadataItem *i in artworks)
            {
                NSString *keySpace = i.keySpace;
                
                if ([keySpace isEqualToString:AVMetadataKeySpaceID3])
                {
                    NSDictionary *d = [i.value copyWithZone:nil];
                    im = [[NSImage alloc] initWithData:[d objectForKey:@"data"]];
                }
                else if ([keySpace isEqualToString:AVMetadataKeySpaceiTunes])
                    im = [[NSImage alloc] initWithData:[i.value copyWithZone:nil]];
                
            }
            
            NSMutableDictionary * di =[NSMutableDictionary dictionary];
            if (im) {
                [di setObject:im forKey:HArtwork];
            }
            
            completion(di);
            
        }];
    }

    
    
}

#pragma mark------写入aac/m4a tag信息
+(void)writeSongInnerArtWorkWithPath:(NSString*)path image:(NSImage*)image{
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        
        NSError *error;
        AVAssetWriter *assetWrtr = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:path] fileType:AVFileTypeAppleM4A error:&error];
        NSLog(@"write error:%@",error);
        
        if(error || !image)return;
        

        NSArray *existingMetadataArray = assetWrtr.metadata;
        NSMutableArray *newMetadataArray = nil;
        if (existingMetadataArray)
        {
            newMetadataArray = [existingMetadataArray mutableCopy]; // To prevent overriding of existing metadata
        }
        else
        {
            newMetadataArray = [[NSMutableArray alloc] init];
        }
        
        
        
        
        
        
        AVMutableMetadataItem *item = [[AVMutableMetadataItem alloc] init];
        item.keySpace = AVMetadataKeySpaceCommon;
        item.key = AVMetadataCommonKeyArtwork;
        
         NSData *customimageData =[HCoreConfig imageConvertData:image imageFileType:NSJPEGFileType fitDeviceScale:NO];
        item.value = customimageData;
        
        [newMetadataArray addObject:item];
        assetWrtr.metadata = newMetadataArray;
        
        
        
        BOOL ok=[assetWrtr startWriting];
        [assetWrtr startSessionAtSourceTime:kCMTimeZero];
        
    }
    
    
    
    
}


#pragma mark------获取sound property
-(NSUInteger)getSoundDuration:(NSURL*)audioURL{
    
    // debugLog(@"time begin");
    
    NSString * ext=[audioURL.pathExtension lowercaseString];
    
    if([ext isEqualToString:@"flac"] || [ext isEqualToString:@"opus"]) {
        
        @autoreleasepool {
            
            
            ORGMInputUnit *input = [[ORGMInputUnit alloc] init];
            
            if (![input openWithUrl:audioURL]) {
                
                return InvalidSoundDuration;
            }
            
            ORGMConverter *converter = [[ORGMConverter alloc] initWithInputUnit:input];
            
            ORGMOutputUnit *output = [[ORGMOutputUnit alloc] initWithConverter:converter];
            
            [converter setupWithOutputUnit:output];
            
            double time=[output framesToSeconds:input.framesCount];
            NSUInteger milesecond= time*1000 ;
            
            //debugLog(@"time end:%f",time);
            return milesecond;
            
        }
        
        
        
    } else {
        
        AudioFileID audioFile;                                        // 4
        OSStatus theErr = noErr;                                      // 5
        theErr = AudioFileOpenURL((__bridge CFURLRef)audioURL,
                                  kAudioFileReadPermission,
                                  0,
                                  &audioFile);                        // 6
        
        if (theErr!=noErr) {
            
            theErr = AudioFileClose (audioFile);                          // 16
            return InvalidSoundDuration;
        }
        
        // 7
        UInt32 dictionarySize = 0;                                    // 8
        theErr = AudioFileGetPropertyInfo (audioFile,
                                           kAudioFilePropertyInfoDictionary,
                                           &dictionarySize,
                                           0);                        // 9
        //    assert (theErr == noErr);                                     // 10
        
        if (theErr!=noErr) {
            theErr = AudioFileClose (audioFile);
            return InvalidSoundDuration;
        }
        
        CFDictionaryRef dictionary;                                   // 11
        theErr = AudioFileGetProperty (audioFile,
                                       kAudioFilePropertyInfoDictionary,
                                       &dictionarySize,
                                       &dictionary);                  // 12
        
        
        if (theErr!=noErr) {
            theErr = AudioFileClose (audioFile);
            return InvalidSoundDuration;
        }
        // 13
        NSDictionary * dic=(__bridge NSDictionary*)dictionary;
        
           // NSLog (@"song DIC:%@",dic);
        // 14
        
        NSString * seconds=dic[@"approximate duration in seconds"];
        NSUInteger milesecond=seconds.floatValue*1000;
        
        
        CFRelease (dictionary);                                       // 15
        theErr = AudioFileClose (audioFile);                          // 16
        
        
        
        return milesecond;
    }
    
    return InvalidSoundDuration;
}




#pragma mark ------------user Setting

//删除itunes的歌曲是否需要询问
-(BOOL)removeItunesAsk{
    
    NSNumber *  num= [[NSUserDefaults standardUserDefaults] valueForKey:RemoveItunesAsk];
    
    //默认询问
    if ([num isKindOfClass:[NSNull class]] || num==nil) {
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES] forKey:RemoveItunesAsk];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    }
    
    BOOL  flag=num.boolValue;
    
    return flag;
}

-(void)setRemoveItunesAsk:(BOOL)removeItunesAsk{
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:removeItunesAsk] forKey:RemoveItunesAsk];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

//是否自动下载歌词
-(BOOL)autoDownloadLyrics{
    
    NSNumber *  num= [[NSUserDefaults standardUserDefaults] valueForKey:AutoDownloadLyrics];
    
    //默认自动下载歌词
    if ([num isKindOfClass:[NSNull class]] || num==nil) {
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES] forKey:AutoDownloadLyrics];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    }
    
    BOOL  flag=num.boolValue;
    
    return flag;
}

-(void)setAutoDownloadLyrics:(BOOL)autoDownloadLyrics{
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:autoDownloadLyrics] forKey:AutoDownloadLyrics];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

//歌词font size
-(NSUInteger)lyricsFontSize{
    
    NSNumber *  num= [[NSUserDefaults standardUserDefaults] valueForKey:LyricsFontSize];
    
    //默认12
    if ([num isKindOfClass:[NSNull class]] || num==nil) {
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:12] forKey:LyricsFontSize];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return 12;
    }
    
    NSUInteger  fz=num.integerValue;
    
    return fz;
}

-(void)setLyricsFontSize:(NSUInteger)lyricsFontSize{
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInteger:lyricsFontSize] forKey:LyricsFontSize];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

//全屏状态歌词font size
-(NSUInteger)lyricsFullScreenFontSize{
    
    NSNumber *  num= [[NSUserDefaults standardUserDefaults] valueForKey:LyricsFullScreenFontSize];
    
    //默认12
    if ([num isKindOfClass:[NSNull class]] || num==nil) {
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:24] forKey:LyricsFullScreenFontSize];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return 24;
    }
    
    NSUInteger  fz=num.integerValue;
    
    return fz;
}

-(void)setLyricsFullScreenFontSize:(NSUInteger)lyricsFullScreenFontSize{
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInteger:lyricsFullScreenFontSize] forKey:LyricsFullScreenFontSize];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}


//排序方式
-(NSString*)currentSortType{
    
    NSString *  sorttype= [[NSUserDefaults standardUserDefaults] valueForKey:HSongSortType];
    
    //默认按日期,也就是syncid
    if ([sorttype isKindOfClass:[NSNull class]] || sorttype==nil) {
        [[NSUserDefaults standardUserDefaults] setValue:SortByDate forKey:HSongSortType];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return SortByDate;
    }
    
    return sorttype;
    
    
    
}

-(void)setCurrentSortType:(NSString *)currentSortType{
    
    [[NSUserDefaults standardUserDefaults] setValue:currentSortType forKey:HSongSortType];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
    
}



//获取当前播放信息
-(NSMutableDictionary* )currentPlayInfo{
    /*
     #define  HCurrentPlayInfo           @"HCurrentPlayInfo"//最近一次播放的信息 dic
     #define  HVolume                    @"HVolume" nsnumber
     #define  HPlayMode                  @"HPlayMode"  // 1 :顺序  2:循环  3:随机 4.单曲循环 nsnumber
     #define  HPlaylistID                @"HPlaylistID" // 当前播放列表ID
     #define  HPlaySongPath              @"HPlaySongpath" // 当前播放歌曲路径
     */
    
    if(!_currentPlayInfo) {
        
        NSDictionary * dic= [[NSUserDefaults standardUserDefaults] valueForKey:HCurrentPlayInfo];
        
        if(!dic || [dic isKindOfClass:[NSNull class]]){
            dic=@{HVolume:@100, // 0~100
                  HPlayMode:@1,
                  HPlaylistID:@"",
                  HPlaySongPath:@""};
        }
        
        _currentPlayInfo=[[NSMutableDictionary alloc] initWithDictionary:dic];
        
        
    }
    return _currentPlayInfo;
    
}



#pragma mark --------itunes相关操作

#pragma mark 保存当前播放信息
-(void)savePlayInfo{
    [[NSUserDefaults standardUserDefaults] setValue:self.currentPlayInfo forKey:HCurrentPlayInfo];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}


#pragma mark 通过itunes app获取音乐库音乐
+(SBElementArray*)getItunesLibraryTracks{
    
    
    SBElementArray *iTunesSources = [[HCoreConfig shareConfig].iTunes sources];
    iTunesSource *library;
    for (iTunesSource *thisSource in iTunesSources) {
        if ([thisSource kind] == iTunesESrcLibrary) {
            library = thisSource;
            break;
        }
    }
    
    SBElementArray * thelibraryPlaylists = [library libraryPlaylists];
    
    return thelibraryPlaylists;
    
}

#pragma mark 获取iunes 我最喜爱的歌曲列表 HSongitem
-(NSMutableArray*)getItunesFavouriteSongs{
    
    NSMutableArray * arr=[NSMutableArray arrayWithCapacity:10];
    @autoreleasepool {
        
        //通过itunes读取
        if([[HCoreConfig shareConfig].iTunes isRunning]){
            
            
            SBElementArray * thelibraryPlaylists=[HCoreConfig getItunesLibraryTracks];
            if(thelibraryPlaylists.count>0) {
                iTunesLibraryPlaylist *libraryPlaylist = [thelibraryPlaylists objectAtIndex:0];
                
                SBElementArray * tracksArr=[libraryPlaylist fileTracks];
                
                for (iTunesFileTrack* thetrack in tracksArr) {
                    
                    if(thetrack.rating>75){
                        HSongItem * sitem=[[HSongItem alloc] initWithItuneTrackEntity:thetrack isfavourite:YES];
                        [arr addObject:sitem];
                    }
                    
                }
                
                
                
            }
            
            
        }
        
        //从文件获取
        else {
            
            NSString * itunesLibpath=[HMusicDirectory stringByAppendingPathComponent:@"itunes/iTunes Music Library.xml"];
            
            if ([[NSFileManager defaultManager] fileExistsAtPath:itunesLibpath]) {
                NSData *metaData = [NSData dataWithContentsOfFile:itunesLibpath];
                NSError * error=nil;
                NSDictionary * libDic = [NSPropertyListSerialization propertyListWithData:metaData
                                                                                  options:kCFPropertyListImmutable
                                                                                   format:NULL
                                                                                    error:&error];
                
                if (!error) {
                    // debugLog(@"song lib %@",dic);
                    NSDictionary * tracksDic=libDic[@"Tracks"];//all song
                    
                    /*该方法直接获取我最喜爱的目录,但如果用户删除,就无法获取标记的歌曲
                     //itunes收藏的歌曲(4star以上Rating)
                     NSArray * allPlaylists=libDic[@"Playlists"];
                     NSMutableArray * favouriteTracks=[NSMutableArray arrayWithCapacity:10];
                     for (NSDictionary * playplistDic in allPlaylists) {
                     NSUInteger Distinguished_Kind = ((NSString*)playplistDic[@"Distinguished Kind"]).integerValue;
                     //我最喜爱分类
                     if (Distinguished_Kind==201) {
                     
                     NSArray * playlistItems=playplistDic[@"Playlist Items"];
                     
                     for (NSDictionary * pitemdic in playlistItems) {
                     NSNumber * tackID=pitemdic[@"Track ID"];
                     [favouriteTracks addObject:tackID.stringValue];
                     }
                     
                     break;
                     }
                     
                     
                     
                     }
                     
                     
                     //我最喜爱的tackID
                     for (NSString * trackID in favouriteTracks) {
                     
                     NSDictionary * songitem=[tracksDic objectForKey:trackID];
                     HSongItem * sitem=[[HSongItem alloc] initWithItuneTrackDic:songitem isfavourite:YES];
                     [arr addObject:sitem];
                     }
                     */
                    
                    
                    //大于等于80表示喜欢
                    NSArray * tracks=[tracksDic allKeys];
                    for (NSString * trackID in tracks) {
                        NSDictionary * songitem=[tracksDic objectForKey:trackID];
                        NSString * rating=songitem[@"Rating"];
                        if(rating && rating.integerValue>70) {
                            HSongItem * sitem=[[HSongItem alloc] initWithItuneTrackDic:songitem isfavourite:YES];
                            [arr addObject:sitem];
                        }
                        
                    }
                    
                    
                    
                    
                }
                
                
            }
            
        }
    }
    return arr;
}


#pragma mark 获取iunes 歌曲列表 Hsongitem
-(NSMutableArray*)getItunesSongs{
    
    NSMutableArray * arr=[NSMutableArray arrayWithCapacity:10];
    @autoreleasepool {
        
        //通过itunes读取
        if([[HCoreConfig shareConfig].iTunes isRunning]){
            
            
            SBElementArray * thelibraryPlaylists=[HCoreConfig getItunesLibraryTracks];
            
            if(thelibraryPlaylists.count>0) {
                iTunesLibraryPlaylist *libraryPlaylist = [thelibraryPlaylists objectAtIndex:0];
                
                SBElementArray * tracksArr=[libraryPlaylist fileTracks];
                
                for (iTunesFileTrack* thetrack in tracksArr) {
                    
                    HSongItem * sitem=[[HSongItem alloc] initWithItuneTrackEntity:thetrack isfavourite:NO];
                    
                    [arr addObject:sitem];
                    
                }
                
                
                
            }
            
            
        }
        
        //从文件获取
        else {
            NSString * itunesLibpath=[HMusicDirectory stringByAppendingPathComponent:@"itunes/iTunes Music Library.xml"];
            
            if ([[NSFileManager defaultManager] fileExistsAtPath:itunesLibpath]) {
                NSData *metaData = [NSData dataWithContentsOfFile:itunesLibpath];
                NSError * error=nil;
                NSDictionary * libDic = [NSPropertyListSerialization propertyListWithData:metaData
                                                                                  options:kCFPropertyListImmutable
                                                                                   format:NULL
                                                                                    error:&error];
                
                if (!error) {
                    // debugLog(@"song lib %@",dic);
                    NSDictionary * tracksDic=libDic[@"Tracks"];//all song
                    
                    NSArray * tracks=[tracksDic allKeys];
                    for (NSString * trackValue in tracks) {
                        
                        NSDictionary * songitem=[tracksDic objectForKey:trackValue];
                        HSongItem * sitem=[[HSongItem alloc] initWithItuneTrackDic:songitem isfavourite:NO];
                        [arr addObject:sitem];
                        
                    }
                    
                }
                
                
            }
            
        }
    }
    return arr;
}


#pragma mark 删除iunes歌曲
+(void)testItunes{
    
    
    
    
    SBElementArray *iTunesSources = [[HCoreConfig shareConfig].iTunes sources];
    iTunesSource *library;
    for (iTunesSource *thisSource in iTunesSources) {
        if ([thisSource kind] == iTunesESrcLibrary) {
            library = thisSource;
            break;
        }
    }
    SBElementArray * thelibraryPlaylists = [library libraryPlaylists];
    
    iTunesLibraryPlaylist *libraryPlaylist = [thelibraryPlaylists objectAtIndex:0];
    
    SBElementArray * tracksArr=[libraryPlaylist fileTracks];
    
    for (iTunesFileTrack * thetrack in tracksArr) {
        
        HSongItem * sitem=[[HSongItem alloc] initWithItuneTrackEntity:thetrack isfavourite:NO];
    }
    
    
    
}


+(void)deleteItunesSongsWithSongitems:(NSArray*)songItems{
    
    
    if ([songItems count]==0) {
        return;
    }
    
    //    [[HCoreConfig shareConfig].iTunes update];
    //   NSUInteger countt= [[HCoreConfig shareConfig].iTunes.currentPlaylist tracks].count;
    //    debugLog(@"countt:%d",countt);
    //    return;
    @autoreleasepool {
        
        /*
         NSString * itunesLibpath=[HMusicDirectory stringByAppendingPathComponent:@"itunes/iTunes Music Library.xml"];
         
         if ([[NSFileManager defaultManager] fileExistsAtPath:itunesLibpath]) {
         NSData *metaData = [NSData dataWithContentsOfFile:itunesLibpath];
         NSError * error=nil;
         NSMutableDictionary * libDic = [NSPropertyListSerialization propertyListWithData:metaData
         options:kCFPropertyListMutableContainersAndLeaves
         format:NULL
         error:&error];
         
         if (!error) {
         
         NSError * error;
         NSFileManager * fm=[NSFileManager defaultManager];
         
         
         // debugLog(@"song lib %@",dic);
         NSMutableDictionary * tracksDic=libDic[@"Tracks"];//all song
         
         //存起所有的要被删除的trackid
         NSMutableArray * trackIDarr=[NSMutableArray arrayWithCapacity:10];
         
         for (HSongItem * sitem in songItems) {
         [trackIDarr addObject:sitem.syncid];
         
         debugLog(@"track id:%@,\npath:%@",sitem.syncid,sitem.localPath);
         
         if ([fm fileExistsAtPath:sitem.localPath]) {
         NSError * error=nil;
         [fm removeItemAtPath:sitem.localPath error:&error];
         
         if(error)debugLog(@"delete song error:%@",error.description);
         
         
         } else {
         debugLog(@"不存在");
         
         }
         
         
         }
         //1.从总的library删除
         [tracksDic removeObjectsForKeys:trackIDarr];//这里的key一定是字符串格式
         
         
         //2.从各个包含这些歌的playlist里面移除
         
         NSMutableArray * allPlaylists=libDic[@"Playlists"];
         NSUInteger playlistsCount=[allPlaylists count];
         
         if(allPlaylists && playlistsCount>0){
         //循环播放列表
         for (int i=0; i<playlistsCount; i++) {
         NSMutableDictionary * pitemDic=[allPlaylists objectAtIndex:i];
         NSMutableArray * playlistitems=pitemDic[@"Playlist Items"];
         
         //如果该播放列表有歌曲
         if(playlistitems && playlistitems.count>0){
         
         //循环检索删掉的歌的tarck id是否相符
         NSMutableIndexSet * deledeIndexS=[NSMutableIndexSet indexSet];
         for (int i=0; i<playlistitems.count; i++) {
         
         NSMutableDictionary * pitemDic=[playlistitems objectAtIndex:i];
         NSString * thetrackid=((NSNumber*)pitemDic[@"Track ID"]).stringValue;
         
         for (NSString * trackID in trackIDarr) {
         if ([thetrackid isEqualToString:trackID]) {
         [deledeIndexS addIndex:i];
         break;
         }
         }
         
         }
         
         
         [playlistitems removeObjectsAtIndexes:deledeIndexS];
         
         
         
         
         }
         
         
         
         }
         
         
         
         }
         
         
         
         
         //3.写回文件
         [libDic writeToFile:itunesLibpath atomically:YES];
         }
         
         
         }
         */
        
        
        SBElementArray * thelibraryPlaylists = [HCoreConfig getItunesLibraryTracks];
        
        if(thelibraryPlaylists.count>0) {
            iTunesLibraryPlaylist *libraryPlaylist = [thelibraryPlaylists objectAtIndex:0];
            
            SBElementArray * tracksArr=[libraryPlaylist fileTracks];
            NSMutableIndexSet * indexset=[NSMutableIndexSet indexSet];
            
            int index=0;
            for (iTunesFileTrack * thetrack in tracksArr) {
                for (HSongItem * songItem in songItems){
                    NSString * localpath=((NSURL*)thetrack.location).path;
                    if([localpath isEqualToString:songItem.localPath]) {
                        //                    debugLog(@"itunes location:%@",loca);
                        //                    debugLog(@"    db location:%@",songItem.localPath);
                        [indexset addIndex:index];
                    }
                }
                
                index++;
            }
            if(indexset.count>0){
                [tracksArr removeObjectsAtIndexes:indexset];
            }
            
            
        }
        
    }
    
    
}

#pragma mark like/unlike iunes歌曲
+(void)likeItunesSongWithSongitem:(HSongItem*)songItem{
    
    @autoreleasepool {
        //通过itunes读取
        //if([[HCoreConfig shareConfig].iTunes isRunning]){
        
        SBElementArray * thelibraryPlaylists=[HCoreConfig getItunesLibraryTracks];
        if(thelibraryPlaylists.count>0) {
            iTunesLibraryPlaylist *libraryPlaylist = [thelibraryPlaylists objectAtIndex:0];
            
            SBElementArray * tracksArr=[libraryPlaylist fileTracks];
            
            for (iTunesFileTrack* thetrack in tracksArr) {
                
                if([thetrack.name isEqualToString:songItem.songName]){
                    thetrack.rating=(songItem.islike?100:0);
                    break;
                }
                
            }
            
            
            
        }
        
        
        //        }
        //        else {
        //            NSString * itunesLibpath=[HMusicDirectory stringByAppendingPathComponent:@"itunes/iTunes Music Library.xml"];
        //            if ([[NSFileManager defaultManager] fileExistsAtPath:itunesLibpath]) {
        //        NSData *metaData = [NSData dataWithContentsOfFile:itunesLibpath];
        //        NSError * error=nil;
        //        NSMutableDictionary * libDic = [NSPropertyListSerialization propertyListWithData:metaData
        //                                                                          options:kCFPropertyListMutableContainersAndLeaves
        //                                                                           format:NULL
        //                                                                            error:&error];
        //
        //        if (!error) {
        //            // debugLog(@"song lib %@",dic);
        //            NSDictionary * tracksDic=libDic[@"Tracks"];//all song
        //
        //            //检查这首歌是否存在itunes里面,用track id
        //            if ([tracksDic objectForKey:songItem.syncid]) {
        //
        //                NSString * songKeypath=[NSString stringWithFormat:@"Tracks.%@.Rating",songItem.syncid];
        //
        //                if(songItem.islike)
        //                [libDic setValue:@"100" forKeyPath:songKeypath];
        //                else
        //                [libDic setValue:@"0" forKeyPath:songKeypath];
        //
        //                //写回文件
        //                [libDic writeToFile:itunesLibpath atomically:YES];
        //
        //
        //            }
        //
        //        }
        //
        //
        //    }
        //        }
        
    }
    
}

//对itunes的歌曲进行编辑(该方法适用于rename文件导致path更改),分启动和未启动
+(void)editItunesNameSongWithSongitem:(HSongItem*)songItem andNewname:(NSString * )theNewName{
    
    @autoreleasepool {
        //通过itunes修改
        SBElementArray * thelibraryPlaylists=[HCoreConfig getItunesLibraryTracks];
        if(thelibraryPlaylists.count>0) {
            iTunesLibraryPlaylist *libraryPlaylist = [thelibraryPlaylists objectAtIndex:0];
            
            SBElementArray * tracksArr=[libraryPlaylist fileTracks];
            
            for (iTunesFileTrack* thetrack in tracksArr) {
                
                 NSURL * oldpathurl=thetrack.location;
                 NSString * oldpath=oldpathurl.path;
               // debugLog(@"old path:%@",oldpath);
                if([oldpath isEqualToString:songItem.localPath]){

                    
                    thetrack.name=theNewName;//由于改了名字,path会跟着改变
                    
                    NSURL * pathurl=thetrack.location;
                    songItem.localPath=pathurl.path;
                    
                    
                    //debugLog(@"new path:%@",pathurl.path);
                    
                    //itunes改变,播放列表要跟着改变
                    [HSQLManager updateSongName:theNewName path:songItem.localPath oldPath:oldpath];
                    
                    //播放队列更改
                    [[HJAudioPlayer sharePlayer] updateQueueSongName:theNewName path:songItem.localPath oldPath:oldpath];
                    
                    break;
                }
                
            }
            
            
            
        }
        
        
        
        
        
    }
    
}

//根据歌曲路径生成songitems ,playlistType: favourite=1 ,导入时候用的
+(NSArray*)getSongItemsWithAudiopaths:(NSArray*)paths type:(NSUInteger)playlistType{
    
    NSMutableArray * songsArr=[NSMutableArray arrayWithCapacity:10];
    
    
    for (NSString * path in paths) {
        NSURL * fileurl=[[NSURL alloc] initFileURLWithPath:path];
        //如果能获取到duration,视为合法音乐格式
        NSUInteger duration=[[HCoreConfig shareConfig] getSoundDuration:fileurl];
        if (duration!=InvalidSoundDuration) {
            
            
            TagReader *t = [[TagReader alloc] initWithFileAtPath:path];
            
            HSongItem * songItem=[[HSongItem alloc] init];
            
            //song localpath
            songItem.localPath=path;
            
            //song name
            if (t.title==nil) {
                NSString * filename=[[path lastPathComponent] stringByDeletingPathExtension];
                songItem.songName=filename;
                //debugLog(@"name:%@",songItem.songName);
            } else {
                songItem.songName=t.title;
            }
            
            //duration
            songItem.songDuration=duration;
            
            //song type
            songItem.songType=CHECKSTR(path.pathExtension);
            
            
            //artist
            songItem.artist=CHECKSTR(t.artist);
            
            //album
            songItem.album=CHECKSTR(t.album);
            
            
            songItem.islike=(playlistType==1?YES:NO);
            
            
            //bookmark
            //创建score bookmark
            NSError * bookmarkerror=nil;
            NSData * data =[fileurl bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
                             includingResourceValuesForKeys:nil
                                              relativeToURL:nil
                                                      error:&bookmarkerror];
            
            
            if (bookmarkerror) {
                debugLog(@"insert song bookmarkerror:%@",bookmarkerror.description);
            } else {
                songItem.bookmark=data;
                
            }
            
            
            
            [songsArr addObject:songItem];
        }
        
        
        
        
        
    }
    
    
    return songsArr;
}

//导入歌曲到itunes的tracks
+(BOOL)importSongToItunesWithpath:(id)path{
    
    NSURL* url=([path isKindOfClass:[NSURL class]] ? path:[NSURL fileURLWithPath:path]);
    iTunesTrack * track = [[HCoreConfig shareConfig].iTunes add:[NSArray arrayWithObject:url] to:nil];//nil的话会插入到tracks标下,
    BOOL res=(track?YES :NO);
    return  res;
}

//根据路径找出itunesfiletack
+(iTunesFileTrack*)getItunesFiletrackWithPath:(NSString*)path{
    
    if([path isEqualToString:@""]) {
    
        return nil;
    }
    
    iTunesFileTrack* thefildtrack=nil;

    SBElementArray * thelibraryPlaylists=[HCoreConfig getItunesLibraryTracks];
    if(thelibraryPlaylists.count>0) {
        iTunesLibraryPlaylist *libraryPlaylist = [thelibraryPlaylists objectAtIndex:0];
        
        SBElementArray * tracksArr=[libraryPlaylist fileTracks];
        
        for (iTunesFileTrack* thetrack in tracksArr) {
            
            NSURL * oldpathurl=thetrack.location;
            NSString * oldpath=oldpathurl.path;
            // debugLog(@"old path:%@",oldpath);
            if([oldpath isEqualToString:path]){
            
                thefildtrack=thetrack;
                break;
            }
        }
    }
    
    return  thefildtrack;
}


//使用路径判断歌曲是否来自itunes library
+(BOOL)checkSongisBelongToItunesWithPath:(NSString*)path{
    
    
    if ([path rangeOfString:@"/iTunes/iTunes Media/Music/"].location == NSNotFound) {
        return NO;
    } else {
        return YES;
    }
    
    
    return NO;
}


+(void)updateItunes{
    
    [[HCoreConfig shareConfig].iTunes update];
    
}

#pragma mark 打开/关闭AccessingSecurityScoped----
+(BOOL)openFilesAccessingSecurityScopedWithSongItem:(HSongItem*)songItem{
    
    
    NSString * localpath=CHECKSTR(songItem.localPath);
    NSString * urlpath=CHECKSTR(songItem.urlPath) ;
    
    if(![localpath isEqualToString:@""]) {
        
        BOOL cansccess= [[NSFileManager defaultManager] isReadableFileAtPath:localpath];
        if (!cansccess) {
            //文件不存在
            if ([[NSFileManager defaultManager] fileExistsAtPath:localpath]==NO) {
                return NO;
            }
            
            
            
            NSData * bookmarkData=songItem.bookmark;
            
            if (bookmarkData) {
                
                NSError * error=nil;
                BOOL  stale=NO;
                NSURL*  bookmark = [NSURL URLByResolvingBookmarkData:bookmarkData options:NSURLBookmarkResolutionWithSecurityScope
                                                       relativeToURL:nil
                                                 bookmarkDataIsStale:&stale
                                                               error:&error];
                if (bookmark==nil) {
                    debugLog(@"solve bookmark error");
                } else if (stale) {
                    debugLog(@"bookmark data need to update , create & store");
                    
                    [HSQLManager updateBookmakrDataWithSongItem:songItem];
                    
                    bookmark = [NSURL URLByResolvingBookmarkData:songItem.bookmark options:NSURLBookmarkResolutionWithSecurityScope
                                                   relativeToURL:nil
                                             bookmarkDataIsStale:&stale
                                                           error:&error];
                    return  [bookmark startAccessingSecurityScopedResource];
                    
                }
                else {
                    return  [bookmark startAccessingSecurityScopedResource];
                }
                
                
            }
            
        } else {
            
            return YES;
            
        }
        
        
        
    }else if (![urlpath isEqualToString:@""]) {
        
        
        return YES;
        
    }
    
    
    return NO;
}


+(void)stopFilesAccessingSecurityScopedWithSongItem:(HSongItem*)songItem{
    
    
    NSString * localpath=CHECKSTR(songItem.localPath);
    
    if(![localpath isEqualToString:@""]) {
       // debugLog(@"close bookmark song:%@",songItem.songName);
        NSURL * fileUrl=[NSURL fileURLWithPath:localpath];
        
        [fileUrl stopAccessingSecurityScopedResource];
        
    }
    
}

#pragma mark -----控件处理----

#pragma mark 弹出警告框
+(void)alertWithTitle:(NSString*)title window:(NSWindow*)window{

    NSBeginCriticalAlertSheet(nil,
                              @"OK",
                              nil,
                              nil,
                              window,
                              self,
                              nil,
                              NULL,
                              NULL,
                              title);


}

#pragma mark 设置NSButton normal /helighted 颜色
+(void)configButton:(NSButton*)button Title:(NSString *)title normalColor:(NSColor*)normalColor helightedColor:(NSColor*)helightedColor shadow:(NSShadow*)shadow{
    
    [button setTitle:title];
    
    //normal
    NSMutableAttributedString *colorTitle =
    [[NSMutableAttributedString alloc] initWithAttributedString:[button attributedTitle]];
    NSRange titleRange = NSMakeRange(0, [colorTitle length]);
    [colorTitle addAttribute:NSForegroundColorAttributeName
                       value:normalColor
                       range:titleRange];
    //如果有阴影
    if (shadow) {
        [colorTitle addAttribute:NSShadowAttributeName
                           value:shadow
                           range:titleRange];
    }
    
    
    
    //highlight
    NSMutableAttributedString * alternatecolorTitle =[[NSMutableAttributedString alloc] initWithAttributedString:[button attributedTitle]];
    
    
    [alternatecolorTitle addAttribute:NSForegroundColorAttributeName
                                value:helightedColor
                                range:titleRange];
    
    [alternatecolorTitle addAttribute:NSFontAttributeName
                                value:button.font
                                range:titleRange];
    
    
    
    
    
    
    [button setAttributedTitle:colorTitle];
    [button setAttributedAlternateTitle:alternatecolorTitle];
}


#pragma mark 设置NSMenuItem title  颜色
+(void)configMsnuItem:(NSMenuItem*)menuItem Title:(NSString *)title normalColor:(NSColor*)normalColor shadow:(NSShadow*)shadow{
    
    //normal
    NSMutableAttributedString *colorTitle =
    [[NSMutableAttributedString alloc] initWithString:title];
    
    
    NSRange titleRange = NSMakeRange(0, [colorTitle length]);
    [colorTitle addAttribute:NSForegroundColorAttributeName
                       value:normalColor
                       range:titleRange];
    //如果有阴影
    if (shadow) {
        [colorTitle addAttribute:NSShadowAttributeName
                           value:shadow
                           range:titleRange];
    }
    
    
    
    [menuItem setAttributedTitle:colorTitle];
    
}



#pragma mark 为NSbutton设置menu
+(void)setButton:(NSButton*)sender menu:(NSMenu*)themenu offset:(NSPoint)point{
    
    NSRect frame = [(NSButton *)sender frame];
    NSPoint menuOrigin = [[(NSButton *)sender superview] convertPoint:NSMakePoint(frame.origin.x+point.x, frame.origin.y+point.y) toView:nil];
    
    NSEvent *event =  [NSEvent mouseEventWithType:NSLeftMouseDown
                                         location:menuOrigin
                                    modifierFlags:NSLeftMouseDownMask
                                        timestamp:0
                                     windowNumber:[[(NSButton *)sender window] windowNumber]
                                          context:[[(NSButton *)sender window] graphicsContext]
                                      eventNumber:0
                                       clickCount:1
                                         pressure:1];
    
    // contextMenu可以直接在XIB里初始化一个菜单
    [NSMenu popUpContextMenu:themenu withEvent:event forView:(NSButton *)sender];
    
  
}


#pragma mark 导出面板
+(void)saveWithWindow:(NSWindow*)window panel:(NSOpenPanel*)panel completionHandler:(void(^)(NSInteger result))handel{
    
    [panel beginSheetModalForWindow:window completionHandler:handel];
    
}


#pragma mark cmyk to rgba
+(NSString*)rgbaColorValueWithCmykColor:(NSColor*)cmykColor {
    
    
    NSString * colorspacename=[cmykColor colorSpaceName];
    
    //    debugLog(@"colorSpaceName:%@",[acolor colorSpaceName]);
    //
    
    if ([colorspacename isEqualToString:@"NSCalibratedWhiteColorSpace"] ||[colorspacename isEqualToString:@"NSCalibratedRGBColorSpace"] || [colorspacename isEqualToString:@"NSDeviceRGBColorSpace"]) {
        return @"0.0,0.0,0.0,0.0";
    }
    
    CGFloat  c=cmykColor.cyanComponent;
    CGFloat  m=cmykColor.magentaComponent;
    CGFloat  y=cmykColor.yellowComponent;
    CGFloat  k=cmykColor.blackComponent;
    CGFloat  alpha=cmykColor.alphaComponent;
    
    CGFloat r=(1.0-c)*(1.0-k);
    CGFloat g=(1.0-m)*(1.0-k);
    CGFloat b=(1.0-y)*(1.0-k);
    
    NSString * str=[NSString stringWithFormat:@"%f,%f,%f,%f",r,g,b,alpha];
    
    return str;
    
}


#pragma mark complement color of  rgba
+(NSString*)complementaryColorrgbaColor:(NSString*)rgbas{
    
    NSArray * ccoms=[rgbas componentsSeparatedByString:@","];
    
    
    NSString *  r=ccoms[0];
    NSString *  g=ccoms[1];
    NSString *  b=ccoms[2];
    NSString *  alpha=ccoms[3];
    
    
    NSString * comcolorValue=[NSString stringWithFormat:@"%f,%f,%f,%f",1.0-r.floatValue,1.0-g.floatValue,1.0-b.floatValue,alpha.floatValue];
    
    return comcolorValue;
    
}


#pragma mark 获取处理过颜色的图片,name不带exention,必须是png,能处理alpha
-(NSImage*)getImageWithMainBundle:(NSString*)name{
    
    //    debugLog(@"bundlePath:%@",[NSBundle mainBundle].bundlePath);
    //debugLog(@"resource:%@",[NSBundle mainBundle].resourcePath);
    //
    //
    //
    //NSString * filename=[name stringByAppendingString:@".tiff"];
    
    //COMBINE_HIDPI_IMAGES to Yes. xcode 会自动把不同的分辨率的图片压缩到tiff里面
    
    @autoreleasepool {
        
        NSString * path=[[NSBundle mainBundle] pathForResource:name ofType:@"tiff"];
        NSString * keypath=[@"imageColor." stringByAppendingString:name];
        NSString * colorValue=[self.currentSkinManager.currentConfigDic valueForKeyPath:keypath];
        
        if (colorValue) {
            NSArray * colorcomponents=[colorValue componentsSeparatedByString:@","];
            CGFloat  red =((NSString*)colorcomponents[0]).floatValue;
            CGFloat  green =((NSString*)colorcomponents[1]).floatValue;
            CGFloat  blue =((NSString*)colorcomponents[2]).floatValue;
            CGFloat  alpha =((NSString*)colorcomponents[3]).floatValue;
            
            CIImage * colorimg=[CIImage imageWithColor:[CIColor colorWithRed:red green:green blue:blue alpha:alpha]];
            CIImage * sourceImage = [CIImage imageWithContentsOfURL:[NSURL fileURLWithPath:path]];
            [self.colorFilter setDefaults];
            
            [self.colorFilter setValue:colorimg forKey:kCIInputImageKey];
            [self.colorFilter setValue:sourceImage forKey:@"inputBackgroundImage"];
            
            CIImage * resultimg=[self.colorFilter valueForKey:kCIOutputImageKey];
            NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCIImage:resultimg];
            
            NSData *pngdata = [rep representationUsingType:NSPNGFileType properties:nil];
            //[pngdata writeToFile:@"/Users/hament/Desktop/hello.png" atomically:YES];
            [self.colorFilter setDefaults];
            return [[NSImage alloc] initWithData:pngdata];
            
            
        } else {
            
            
            return  [[NSImage alloc] initWithContentsOfFile:path];
            
        }
        
    }
    
    return nil;
}


-(NSImage*)getImageWithMainBundle:(NSString*)name configDic:(NSDictionary*)configDic{
    
    //    debugLog(@"bundlePath:%@",[NSBundle mainBundle].bundlePath);
    //debugLog(@"resource:%@",[NSBundle mainBundle].resourcePath);
    //
    //
    //
    //NSString * filename=[name stringByAppendingString:@".tiff"];
    
    //COMBINE_HIDPI_IMAGES to Yes. xcode 会自动把不同的分辨率的图片压缩到tiff里面
    
    @autoreleasepool {
        
        NSString * path=[[NSBundle mainBundle] pathForResource:name ofType:@"tiff"];
        NSString * keypath=[@"imageColor." stringByAppendingString:name];
        NSString * colorValue=[configDic valueForKeyPath:keypath];
        
        if (colorValue) {
            NSArray * colorcomponents=[colorValue componentsSeparatedByString:@","];
            CGFloat  red =((NSString*)colorcomponents[0]).floatValue;
            CGFloat  green =((NSString*)colorcomponents[1]).floatValue;
            CGFloat  blue =((NSString*)colorcomponents[2]).floatValue;
            CGFloat  alpha =((NSString*)colorcomponents[3]).floatValue;
            
            CIImage * colorimg=[CIImage imageWithColor:[CIColor colorWithRed:red green:green blue:blue alpha:alpha]];
            CIImage * sourceImage = [CIImage imageWithContentsOfURL:[NSURL fileURLWithPath:path]];
            [self.colorFilter setDefaults];
            
            [self.colorFilter setValue:colorimg forKey:kCIInputImageKey];
            [self.colorFilter setValue:sourceImage forKey:@"inputBackgroundImage"];
            
            CIImage * resultimg=[self.colorFilter valueForKey:kCIOutputImageKey];
            NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCIImage:resultimg];
            
            NSData *pngdata = [rep representationUsingType:NSPNGFileType properties:nil];
            //[pngdata writeToFile:@"/Users/hament/Desktop/hello.png" atomically:YES];
            [self.colorFilter setDefaults];
            return [[NSImage alloc] initWithData:pngdata];
            
            
        } else {
            
            
            return  [[NSImage alloc] initWithContentsOfFile:path];
            
        }
        
    }
    
    return nil;
}



#pragma mark 简单图像缩放
+(NSImage *)imageResize:(NSImage*)anImage newSize:(NSSize)newSize {
    NSImage *sourceImage = anImage;
    
    // Report an error if the source isn't a valid image
    if (![sourceImage isValid]){
        debugLog(@"Invalid Image");
    } else {
        NSImage *smallImage = [[NSImage alloc] initWithSize: newSize];
        [smallImage lockFocus];
        [sourceImage setSize: newSize];
        [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
        [sourceImage drawAtPoint:NSZeroPoint fromRect:CGRectMake(0, 0, newSize.width, newSize.height) operation:NSCompositeCopy fraction:1.0];
        [smallImage unlockFocus];
        return smallImage;
    }
    return nil;
}

//返回img data
+(NSData*)imageConvertData:(NSImage*)sourceImage  imageFileType:(NSBitmapImageFileType)imagetype fitDeviceScale:(BOOL)flag{
    
    if (![sourceImage isValid]) {
        debugLog(@"Invalid Image");
        return NO;
    }
    
    NSInteger sizeWidth = sourceImage.size.width;
    NSInteger sizeHeigh = sourceImage.size.height;
    
    
    NSBitmapImageRep *rep;
    
    
    if (flag) {
        NSData *customimageData = [sourceImage TIFFRepresentation];//会根据屏幕生成对应的图片,例如 原图片: 72dpi, 20x20 ,retina屏幕就会绘制成 144dpi, 40x40
        
        rep = [[NSBitmapImageRep alloc] initWithData:customimageData];
        
    }
    else {
        rep = [[NSBitmapImageRep alloc]
               initWithBitmapDataPlanes:NULL
               pixelsWide:sizeWidth
               pixelsHigh:sizeHeigh
               bitsPerSample:8
               samplesPerPixel:4
               hasAlpha:YES
               isPlanar:NO
               colorSpaceName:NSCalibratedRGBColorSpace
               bytesPerRow:0
               bitsPerPixel:0];
        [rep setSize:NSMakeSize(sizeWidth, sizeHeigh)];
        
        [NSGraphicsContext saveGraphicsState];
        [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:rep]];
        [sourceImage drawInRect:NSMakeRect(0, 0, sizeWidth, sizeHeigh) fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
        [NSGraphicsContext restoreGraphicsState];
        
    }
    
    NSData *data = [rep representationUsingType:imagetype properties:nil];
    
    return data;
}


#pragma mark 屏幕坐标截图
+(NSImage *)captureImageForRect:(NSRect)rect {
    CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
    NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:screenShot];
    
    NSImage *result = [[NSImage alloc] init];
    
    [result addRepresentation:imageRep];
    
    return result;
}



#pragma mark窗口截图
+(NSImage*)windowImageShot:(NSWindow*)window
{
    CGWindowID windowID = (CGWindowID)[window windowNumber];
    CGWindowImageOption imageOptions = kCGWindowImageDefault;
    CGWindowListOption singleWindowListOptions = kCGWindowListOptionIncludingWindow;
    CGRect imageBounds = CGRectNull;
    
    CGImageRef windowImage = CGWindowListCreateImage(imageBounds, singleWindowListOptions, windowID, imageOptions);
    NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:windowImage];
    NSImage *result = [[NSImage alloc] init];
    [result addRepresentation:imageRep];
    [result setCacheMode:NSImageCacheNever];
    return result;
    
}
@end
